package com.chiang.apntest.service;


import com.chiang.apntest.common.Constant;
import com.chiang.apntest.manager.XmppConnManager;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * 
 * @author Chiang.C
 * ConnectionListener; PacketListener;
 *
 */
public class SysMessageService extends Service {

	private XmppConnManager mXmppConnManager;
	
	protected static final String TAG = "SysMessageService";
	
	@Override
	public void onCreate() {
		Log.i(TAG, "-------SysMessageService:onCreate()");
		if(null==mXmppConnManager){
			mXmppConnManager=XmppConnManager.getInstance();
			mXmppConnManager.initXmppManager(this);
			mXmppConnManager.startThreadForConnecting();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i(TAG, "-------SysMessageService:onDestroy()");
		if(mXmppConnManager!=null){
			mXmppConnManager.disconnectToHost();
		}
//		XMPPConnection xmppConnection=XmppConnManager.getInstance().getXmppConnection();
//		if(null!=xmppConnection)xmppConnection.removePacketListener(mPacketListener);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		 if (intent != null) {
			 Log.i(TAG, "-------SysMessageService:onStartCommand()--intent isn't null");
			String action = intent.getStringExtra(Constant.ACTION);
			if (action != null && action.equals(Constant.ACTION_CONNECT_XMPP)) {
				String password = intent.getStringExtra(Constant.KEY_PASSWORD);
				String userName = intent.getStringExtra(Constant.KEY_USERNAME);
				connect(userName, password);
			}
		}
		return START_NOT_STICKY;
	}

	private void connect(String username, String password) {
		Log.i(TAG, "-------SysMessageService--connect("+username+", "+password+")");
		if(mXmppConnManager!=null && !mXmppConnManager.isAuthenticated()){
			mXmppConnManager.submitConnectReq(username, password);
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	
}
